{% extends "_base.html" %}
{% block title %}{{ super() }} Items {% endblock %}

{% block extrahead %}
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"/>
    <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
    <style>
        #records-map {
            height: 350px;
        }
    </style>

{% endblock %}

{% block crumbs %}
{{ super() }} /
<a href="{{ config['server']['url'] }}/collections">Collections</a> /
<a href="{{ config['server']['url'] }}/collections/{{ data['collection'] }}">{{ data['title'] }}</a> /
<a href="{{ config['server']['url'] }}/collections/{{ data['collection'] }}/items">Items</a>
{% endblock %}

{% block body %}

<section id="items">

{% set nav_links = namespace(prev=None, next=None, self=None) %}
{% for link in data['links'] %}
{% if link['rel'] == 'prev' %}
{% set nav_links.prev = link['href'] %}
{% endif %}
{% if link['rel'] == 'self' %}
{% set nav_links.self = link['href'] %}
{% endif %}
{% if link['rel'] == 'next' %}
{% set nav_links.next = link['href'] %}
{% endif %}
{% endfor %}

<div class="container-fluid">
  <div class="row">
    <div class="col-lg-6">
      <div id="records-map"></div>
      <div id="facets">
        {% if data['facets'] %}
        {% for facet in data['facets'].keys() %}
        <div class="card mt-3">
          <div class="card-header text-capitalize">{{ facet }}</div>
          <div class="card-body">
            {% for bucket in data['facets'][facet].buckets %}
            <a href="{{ nav_links.self.split('?')[0] }}?{{facet}}={{bucket['value']}}"
              class="text-capitalize">{{bucket['value']}}</a>
            <span class="badge rounded-pill bg-secondary" style="float:right">{{bucket['count']}}</span><br>
            {% endfor %}
          </div>
        </div>
        {% endfor %}
        {% endif %}
      </div>
    </div>
    <div class="col-lg-6">
      {% if nav_links.prev %}
      <a href="{{ nav_links.prev }}"><button type="button" class="btn btn-sm btn-primary">Prev</button></a>
      {% else %}
      <button type="button" class="btn btn-sm btn-primary" disabled>Prev</button>
      {% endif %}
      {% if nav_links.next %}
      <a href="{{ nav_links.next }}"><button type="button" class="btn btn-sm btn-primary">Next</button></a>
      {% else %}
      <button type="button" class="btn btn-sm btn-primary" disabled>Next</button>
      {% endif %}
      <!--<form id="items-query-form" action="{{ config['server']['url'] }}/collections/{{ data['collection'] }}/items">-->
      <form id="items-query-form">
        <input id="q" class="form-control" name="q"/>
      </form>
      <div class="row">
        <table class="table table-striped table-hover" id="items-table-table">
          <thead>
            <tr>
              <th>Title</th>
              <th>Type</th>
            </tr>
          </thead>
          <tbody>
            {% for rec in data['features'] %}
            <tr>
              {% if 'properties' in rec %}
              <td id="{{ rec['id'] }}"><a title="{{ rec['properties'].get('title', rec['id']) }}" href="{{ config['server']['url'] }}/collections/{{ data['collection'] }}/items/{{ rec['id'] }}">{{ rec['properties'].get('title', rec['id']) }}</a></td>
              {% else %}
              <td id="{{ rec['id'] }}"><a title="{{ rec.get('title', rec['id']) }}" href="{{ config['server']['url'] }}/collections/{{ data['collection'] }}/items/{{ rec['id'] }}">{{ rec.get('title', rec['id']) }}</a></td>
              {% endif %}
              {% if 'properties' in rec %}
                {% if 'type' in rec['properties'] %}
                <td>{{ rec['properties']['type'] }}</td>
                {% elif rec.get('type') == 'Feature' and 'stac_version' not in rec %}
                <td>record</td>
                {% elif rec.get('type') == 'Feature' and 'stac_version' in rec %}
                <td>item</td>
                {% else%}
                <td>{{ rec.get('type') }}</td>
                {% endif %}
              {% else %}
                {% if rec.get('type') == 'Feature' and 'stac_version' not in rec %}
                <td>record</td>
                {% elif rec.get('type') == 'Feature' and 'stac_version' in rec %}
                <td>item</td>
                {% elif rec.get('type') == 'Collection' and 'stac_version' in rec %}
                <td>collection</td>
                {% elif rec.get('type') == 'Catalog' and 'stac_version' in rec %}
                <td>catalog</td>
                {% else%}
                <td>{{ rec.get('type') }}</td>
                {% endif %}
              {% endif %}
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
      {% if nav_links.prev %}
      <a href="{{ nav_links.prev }}"><button type="button" class="btn btn-sm btn-primary">Prev</button></a>
      {% else %}
      <button type="button" class="btn btn-sm btn-primary" disabled>Prev</button>
      {% endif %}
      {% if nav_links.next %}
      <a href="{{ nav_links.next }}"><button type="button" class="btn btn-sm btn-primary">Next</button></a>
      {% else %}
      <button type="button" class="btn btn-sm btn-primary" disabled>Next</button>
      {% endif %}
    </div>
  </div>
</div>

</section>

{% endblock %}

{% block extrafoot %}
{% if data['features'] %}
    <script>
    var map = L.map('records-map').setView([0, 0], 1);
    map.addLayer(new L.TileLayer(
        'https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 18,
            attribution: 'Map data &copy; <a href="https://openstreetmap.org/copyright">OpenStreetMap contributors</a>'
        }
    ));
    var geojson_data = {{ data['features'] | to_json }};
    var items = new L.GeoJSON(geojson_data, {
        onEachFeature: function (feature, layer) {
            var url = './items/' + feature.id;
            var html = '<span><a href="' + url + '">' + feature.id + '</a></span>';
            layer._leaflet_id = feature.id;
            layer.bindPopup(html);
        }
    });

    map.addLayer(items);
    var bounds = items.getBounds();
    if (bounds.isValid() === true) {
        map.fitBounds(bounds);
    }

    var highlightStyle = {
        color: 'red',
        dashArray: '',
        fillOpacity: 0.5
    }

    $(document).ready(function() {
        $('#items-table-table tr').on('mouseenter', function(e){
            id_ = $(this).find('[id]').attr('id');
            layer = items.getLayer(id_); //your feature id here
            if (layer) {
                layer.setStyle(highlightStyle);
            }
        }).on('mouseout', function(e){
            id_ = $(this).find('[id]').attr('id');
            layer = items.getLayer(id_); //your feature id here
            items.resetStyle(layer);
        });
        $("#q").on("keypress", function(event){
            if (event.which == 13 && !event.shiftKey) {
                event.preventDefault();

                var queryParams = new URLSearchParams(window.location.search);
                queryParams.set("q", $("#q").val());
                var new_url = '{{ config['server']['url'] }}/collections/{{ data['collection'] }}/items?' + queryParams.toString();
                window.location = new_url;
            }
        });
    });
    </script>
{% endif %}
{% endblock %}
